import axios from 'axios'
// eslint-disable-next-line no-unused-vars
import { Message, MessageBox } from 'element-ui'

const baseURL = process.env.NODE_ENV === 'production' ? '/' : '/api'

const service = axios.create({
  baseURL,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    config.headers['Token'] = localStorage.getItem('Token')
    return config
  },
  error => {
    console.log(error) // for debug
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    console.log(response)
    const res = response.data
    if (res.code !== 200) {
      /* Message({
        type: 'error',
        message: res.msg || '未知错误'
      }) */

      // 未登录弹窗
      if (res.code === 508 || res.code === 512 || res.code === 514) {
        MessageBox.confirm(
          '监测到您还未登录，将使用离线数据为您提供服务，为了避免丢失数据和配置，建议登录后使用。',
          '登出提示',
          {
            confirmButtonText: '马上登录',
            cancelButtonText: '近期不再提示',
            type: 'warning'
          }
        )
          .then(() => {
            console.log('confirm')
            // todo redirect to /login
            this.$router.push('/login')
          })
          .catch(() => {
            console.log('cancel')
            // todo set localStorage 'no-tips'
          })
      }

      return Promise.reject(res.msg)
    } else {
      // setTimeout for test loading
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(res)
        }, 1000)
      })
    }
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

export default service
